package com.wanxi.interceptor;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * Created by IntelliJ IDEA.
 * 统计controller内的方法运行一次需要多长时间
 * @Author : 林子淳
 * @create 2023/3/14 13:31
 */
public class ProcedureWorkpieceRatio implements HandlerInterceptor {
    private Jedis jedis = new Jedis();
    long stime;
    long etime;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在拦截点执行前拦截，如果返回true则不执行拦截点后的操作（拦截成功）
        //开始时间
        if (handler instanceof HandlerMethod) {
            //设置时间格式
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            //获取当前时间毫秒数，开始时间
            stime =System.currentTimeMillis();

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (handler instanceof HandlerMethod) {
            //获取头部信息
            HandlerMethod h = (HandlerMethod) handler;
            //设置时间格式
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            //获取当前时间毫秒数，结束时间
            etime = System.currentTimeMillis();
            //h.getMethod().getName():获取当前的拦截的方法名
            System.out.println("用户想执行的操作是:" + h.getMethod().getName()  + "开始时间" + df.format(stime)+ "结束时间" + df.format(etime)+",执行时长："+(etime-stime));
            BufferedWriter bufferedWriter = null;
            try {
                //把获取的信息存储到txt文件中
                bufferedWriter = new BufferedWriter(new FileWriter("E:\\wanxi_java_project\\six-stage\\healthcare04_0222\\PMA_PerformanceMonitoringofApplication.txt",true));
                bufferedWriter.write("用户想执行的操作是:" + h.getMethod().getName()  + "开始时间" + df.format(stime)+ "结束时间" + df.format(etime)+",执行时长："+(etime-stime));
                bufferedWriter.newLine();
                bufferedWriter.flush();
            } catch (IOException ex) {
                ex.printStackTrace();
            }finally {
                try {
                    bufferedWriter.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在处理过程中，执行拦截

    }
}
